package com.hqyj.springBoot.modules.account.dao;

import com.hqyj.springBoot.modules.common.vo.Search;
import com.hqyj.springBoot.modules.account.entity.User;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

@Mapper
@Repository
public interface UserDao {

    @Select("select * from account_user where user_name = #{userName} and password = #{password}")
    User getUserByUserNameAndPassword(@Param("userName") String userName, @Param("password") String password);

    @Insert("insert into account_user (create_date,email,user_name,password,user_image) " +
            "values(#{createDate},#{email},#{userName},#{password},#{userImage}) ")
    //将自动生成的id给返回来
    @Options(useGeneratedKeys = true,keyColumn = "id",keyProperty = "userId")
    void insertUser(User user);


    @Select("select * from account_user where user_name = #{userName} limit 1")
    User selectOneByUserName(String userName);


    @Update("update account_user set user_name = #{userName},email = #{email},create_date = #{createDate}," +
            "password = #{password} ,user_image = #{userImage} " +
            "where id = #{userId}")
    void updateUser(User user);


    @Delete("delete from account_user where id = #{userId}")
    void deleteUserById(int userId);


    @Select("select * from account_user where id = #{userId}")
    @Results(id = "userResults",value = {
            @Result(column = "id", property = "userId"),
            @Result(column = "id",property = "roles",javaType = List.class,
                    many = @Many(select = "com.hqyj.springBoot.modules.account.dao.RoleDao.getRolesByUserId"))
    }
    )
    User selectUserById(int userId);

    @Select("<script>" +
            "select * from account_user " +
            "<where>" +
            "<if test='keyword != \"\" and keyword != null'>"+
            "and (user_name like '%${keyword}%' " +
            "or email like '%${keyword}%')" +
            "</if>"+
            "</where>"+
            "<choose>"+
            "<when test='sort != \"\" and sort != null'>"+
            "order by ${sort} ${direction}"+
            "</when>"+
            "<otherwise>"+
            "order by id desc"+
            "</otherwise>"+
            "</choose>"+
            "</script>")
    @Results(id = "searchResults",value = {
            @Result(column = "id", property = "userId"),
            @Result(column = "id",property = "roles",javaType = List.class,
                    many = @Many(select = "com.hqyj.springBoot.modules.account.dao.RoleDao.getRolesByUserId"))
    }
    )
    List<User> getUserBySearch(Search search);

}
